<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <el-table v-loading="isLoading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" class="avatar" :src="row.staffPhoto" alt="" @click="showAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="{row}">
              <!-- el-switch 可以 v-model 绑定一个布尔值
              但是现在我们没有布尔值，也不需要双向绑定 -->
              <!-- v-model 其实是:value 和 @input 的合并语法糖 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button v-if="checkPerm('aa')" type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <Addemployee :show-dialog.sync="showDialog" />
      <el-dialog title="头像" :visible.sync="isShowAvatar">
        <el-row type="flex" justify="center">
          <canvas ref="avatarQRCode" />
        </el-row>
      </el-dialog>
      <AssignRole ref="assignRole" :show-dialog.sync="showRoleDialog" :employee-id="employeeId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EnumEmployee from '@/api/constant/employees'
import { formatDate } from '@/filters'
import Addemployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import QRCode from 'qrcode'

// 局部引入
// import { checkPermMixin } from '@/mixin'
export default {
  // filters: {
  //   formatDate(oldVal) {
  //     return oldVal.split('T')[0]
  //   }
  // },
  components: {
    Addemployee,
    AssignRole
  },
  // mixins: [checkPermMixin],
  data() {
    return {
      showRoleDialog: false,
      isShowAvatar: false,
      showDialog: false,
      isLoading: false,
      employeeId: '',
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      }
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // checkPerm(pointName) {
    //   // 从个人数据的points权限列表中判断, 是否有这个传入名字
    //   return this.$store.state.user.userInfo.roles.points.includes(pointName)
    // },
    async getEmployeeList() {
      this.isLoading = true
      const { rows, total } = await getEmployeeList(this.page)
      // 假设本地数据库没有 enableState 默认加上
      this.list = rows.map(item => ({ ...item, enableState: item.enableState || 1 }))
      this.page.total = total
      console.log(this.list)
      this.isLoading = false
      // const res = await getEmployeeList()
      // console.log(res)
    },
    currentChange(newPage) {
      // 1 更新页码配置
      this.page.page = newPage
      // 2 发请求
      this.getEmployeeList()
    },
    formatEmployment(row, col, cell, index) {
      const obj = EnumEmployee.hireType.find(item => Number(item.id) === Number(cell))
      return obj ? obj.value : '未知形式'
    },
    async exportExcel() {
      // 数据获取
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      console.log(rows)

      // 2. 数据转换
      // header
      // data
      // 两个数据都按照字典顺序排列就可以保证生成结果的顺序正确
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      const header = Object.keys(dict)
      console.log(header)

      const newData = rows.map(user => {
        return this.obj2Arr(user, dict)
      })
      console.log(newData)
      // data

      // 3. excel生成
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      // console.log(export_json_to_excel)
      export_json_to_excel({
        header,
        data: newData
      })
    },
    obj2Arr(user, dict) {
      const res = []
      console.log(user)
      // 转换逻辑
      // 我们有一个单对象类型的员工
      // 我们还有字典，字典是用来确定顺序的
      // 只需要按顺序遍历字典，每个 key 都去拿 value 放入数组
      for (const key in dict) {
        const enKey = dict[key]
        let value = user[enKey]
        // 如果是聘用形式
        if (enKey === 'formOfEmployment') {
          const obj = EnumEmployee.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        // 如果是时间
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = formatDate(value)
        }
        res.push(value)
      }
      console.log(res)
      return res
    },
    async delEmployee(id) {
      // 二次询问
      await this.$confirm(this.$t('confirmDel'))
      // 发送请求
      await delEmployee(id)
      // 提醒用户
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page.page > 1) {
        this.page.page--
      }
      // 更新页面
      this.getEmployeeList()
    },
    showAvatar(imgUrl) {
      if (imgUrl) {
        this.isShowAvatar = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.avatarQRCode, imgUrl,
            {
              width: 300,
              color: {
                dark: '#66b1ff'
              }
            }
          )
        })
      }
    },
    async  assignRole(id) {
      // 给一个异步操作 让他弹窗之前先异步执行完在弹窗
      await this.$refs.assignRole.getUserDetail(id)
      this.employeeId = id
      this.showRoleDialog = true
    }

  }
}
</script>
<style lang="scss" scoped>
.avatar{
  width: 200px;
  height: 130px;
  object-fit: contain;
}
</style>
